package aex.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpRequest {
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
    	  URL localURL;
    	  StringBuffer resultBuffer = new StringBuffer();
		try {
			localURL = new URL(url);
          URLConnection connection = localURL.openConnection();
          HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
          
          httpURLConnection.setRequestProperty("Accept-Charset", "GBK");
          httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          
          InputStream inputStream = null;
          InputStreamReader inputStreamReader = null;
          BufferedReader reader = null;
          String tempLine = null;
          
          if (httpURLConnection.getResponseCode() >= 300) {
              throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
          }
          
          try {
              inputStream = httpURLConnection.getInputStream();
              inputStreamReader = new InputStreamReader(inputStream);
              reader = new BufferedReader(inputStreamReader);
              
              while ((tempLine = reader.readLine()) != null) {
                  resultBuffer.append(tempLine);
              }
              
          } finally {
              
              if (reader != null) {
                  reader.close();
              }
              
              if (inputStreamReader != null) {
                  inputStreamReader.close();
              }
              
              if (inputStream != null) {
                  inputStream.close();
              }
              
          }
          
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultBuffer.toString();
    }

}
